package com.rykj.qxj.server.services.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rykj.qxj.server.dao.TaskHistoryMapper;
import com.rykj.qxj.server.dao.TaskMapper;
import com.rykj.qxj.server.model.entity.FieldRule;
import com.rykj.qxj.server.model.entity.FieldTask;
import com.rykj.qxj.server.model.entity.Task;
import com.rykj.qxj.server.model.entity.TaskHistory;
import com.rykj.qxj.server.services.IQuartzService;
import com.rykj.qxj.server.services.ITaskService;
import com.rykj.qxj.server.util.object.StringUtils;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("taskService")
@Log4j
public class TaskServiceImpl implements ITaskService {

    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private TaskHistoryMapper taskHistoryMapper;
    @Autowired
    private IQuartzService quartzService;

    @Override
    public void saveTask(Task task) throws  Exception{
        taskMapper.saveTask(task);
        int  taskId = task.getId();
        List<FieldTask> fieldTasks = task.getFieldTasks();
        if (!CollectionUtils.isEmpty(fieldTasks)){
            fieldTasks.forEach(t->{
                if(t.getFieldId()==0){
                    log.error("没有填写字段");
                    try {
                        throw  new Exception("缺少校验字段");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                t.setTaskId(taskId);
            });
            taskMapper.saveFieldTasks(fieldTasks);
            List<FieldRule> fieldRules = task.getFieldRules();
            if (!CollectionUtils.isEmpty(fieldRules)){
                if(fieldRules.get(0).getFieldId()==0){
                    log.error("没有填写字段");
                    try {
                        throw  new Exception("缺少校验字段");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                taskMapper.saveFieldRules(fieldRules);
            }
        }
        try {
            quartzService.addJob(task.getTaskName(),task.getId(),task.getExecuteRate());
        } catch (Exception e) {
            log.error("任务队列添加任务失败",e);
            throw  new Exception("任务队列添加任务失败");
        }


    }

    @Override
    public void updateTask(Task task) throws Exception {
        taskMapper.updateTask(task);
        //先删除关联规则
        taskMapper.deleteFieldRules(task);
        //再删除关联字段
        taskMapper.deleteFieldTasks(task);
        List<FieldTask> fieldTasks = task.getFieldTasks();
        if (!CollectionUtils.isEmpty(fieldTasks)){
            taskMapper.saveFieldTasks(fieldTasks);
        }
        List<FieldRule> fieldRules = task.getFieldRules();
        if (!CollectionUtils.isEmpty(fieldRules)){
            taskMapper.saveFieldRules(fieldRules);
        }
        try {
            quartzService.modifyJobTime(task.getTaskName(),task.getId(),task.getExecuteRate());
        } catch (Exception e) {
            log.error("任务队列修改任务失败",e);
            throw  new Exception("任务队列修改任务失败");
        }

    }

    @Override
    public void deleteTask(Integer id,String taskName)throws Exception {
        taskMapper.deleteTask(id);
        try {
            quartzService.removeJob(taskName);
        } catch (Exception e) {
          log.error("任务队列移除任务失败",e);
          throw  new Exception("任务队列移除任务失败");
        }
    }

    @Override
    public Task getTaskDetails(Integer id) {
      Task task = taskMapper.getTaskDetails(id);
      return task;
    }

    @Override
    public PageInfo getTaskList(Integer pageNum, Integer pageSize, String taskName, String tableName, String executeType,
                                String taskStatus,Integer applyId,Integer databaseId,Integer tableId) {
        PageHelper.startPage(pageNum,pageSize);
        Map<String,Object> paraMap = new HashMap<>();
        if("%".equals(taskName)){
            taskName ="\\%";
        }
        if("%".equals(tableName)){
            tableName ="\\%";
        }
        paraMap.put("taskName",taskName);
        paraMap.put("tableName",tableName);
        paraMap.put("executeType",executeType);
        paraMap.put("taskStatus",taskStatus);
        paraMap.put("applyId",applyId);
        paraMap.put("databaseId",databaseId);
        paraMap.put("tableId",tableId);
        List<Map<String,Object>> tasks =  taskMapper.getTaskList(paraMap);
        PageInfo pageInfo = new PageInfo(tasks);
        return  pageInfo;
    }

    @Override
    public PageInfo getAuditMetadataList(Integer pageNum, Integer pageSize,Integer taskId){
        PageHelper.startPage(pageNum,pageSize);
        List<Map<String,Object>> fields=  taskMapper.getAuditMetadataList(taskId);
        if(!CollectionUtils.isEmpty(fields)){
            fields.forEach(f->{
               f.put("rules",taskMapper.getFieldfRules((Integer) f.get("id")));
            });
        }
        PageInfo pageInfo = new PageInfo(fields);
        return  pageInfo;
    }


    @Override
    public PageInfo getUnTaskFields(Integer pageNum, Integer pageSize, Integer tableId) {
        PageHelper.startPage(pageNum,pageSize);
        List<Map<String,Object>> fields=  taskMapper.getUnTaskFields(tableId);
        PageInfo pageInfo = new PageInfo(fields);
        return  pageInfo;
    }

    @Override
    public List<Map<String, Object>> getFieldRules(Integer taskId) {
        return taskMapper.getFieldRules(taskId);
    }

    @Override
    public Map<String, Object> getDatabaseInfoByTaskId(Integer taskId) {
        return taskMapper.getDatabaseInfoByTaskId(taskId);
    }

    @Override
    public void updateTaskStatus(String taskStatus,Integer taskId,String taskName,String time)throws  Exception {
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("taskStatus",taskStatus);
        paraMap.put("taskId",taskId);
        taskMapper.updateTaskStatus(paraMap);
        if(StringUtils.isNotEmpty(time)){
            try {
                quartzService.startOrShutdownJob(taskName,taskStatus,taskId,time);
            } catch (Exception e) {
                log.error("任务队列停止任务失败",e);
                throw  new Exception("任务队列停止任务失败");
            }
        }

    }

    @Override
    public void updateTaskExecuteTime(Integer taskId) {
        taskMapper.updateTaskExecuteTime(taskId);
    }

    /**
     * 服务重启时,重启正常的任务
     * @return
     */
    @Override
    public List<Map<String,Object>> getAllNormalTasks(){
        return  taskMapper.getAllNormalTasks();
    }

    @Override
    public List<Integer> getTaskIdByName(String taskName) {
        return  taskMapper.getTaskIdByName(taskName);
    }


    @Override
    public void saveTaskHistory(TaskHistory taskHistory) {
        taskHistoryMapper.saveTaskHistory(taskHistory);
    }

    @Override
    public void updateTaskHistoryType(TaskHistory taskHistory) {
        taskHistoryMapper.updateTaskHistoryType(taskHistory);
    }
}
